<script setup lang="ts">
import { onMounted, ref,reactive ,onUnmounted} from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { ElTable, ElForm } from 'element-plus';
import Pagination from '@/components/Pagination.vue';

const isLoading = ref(false);
const isBusy = ref(false);
const listDatas = ref(<any[]>[]);
const pageNumber = ref(1);
const servicePath = "/Role";
const total = ref(0);
const formData = ref(<any>{});
var editingData: any;
const dialogFormVisible = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
const formRef = ref<InstanceType<typeof ElForm>>();

const searchData = reactive({
  PageSize:10,
  PageIndex:0
});

const rules = reactive({
  Name: [
    { required: true, message: '请输入代号', trigger: 'blur' }
  ],
  Caption: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
})

onMounted(() => {
 
  bindList();
});

onUnmounted(()=>{
  console.log("卸载了");
});

const refreshClick = () => {
  bindList();
}

const bindList = async () => {
  isLoading.value = true;
  try {
    searchData.PageIndex = pageNumber.value - 1;
    var list = JSON.parse(await HttpHelper.postJson(`${servicePath}/List`, searchData));

    total.value = list.Total;
    listDatas.value.splice(0, listDatas.value.length);
    listDatas.value.push(...list.Datas);

    if (listDatas.value.length == 0 && pageNumber.value > 1) {
      pageNumber.value--;
      bindList();
    }
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;
  }
}

const resetFormData = () => {
  formData.value = {
    Name: "",
    Caption: ""
  };
}

const addClick = () => {
  resetFormData();
  dialogFormVisible.value = true;
}

const editClick = (row: any) => {
  resetFormData();
  for (var p in row) {
      formData.value[p] = row[p];
    
  }
  editingData = row;
  dialogFormVisible.value = true;
}

const deleteClick = async () => {
  if (isLoading.value)
    return;

  if (multipleSelection.value.length == 0) {
    Global.showInfo("请选择需要删除的数据");
    return;
  }

  if (confirm("确定删除吗？")) {
    try {
      isLoading.value = true;
      var requestData = new FormData();
      multipleSelection.value.forEach(x => {
        requestData.append("ids", x.id);

      });
      await HttpHelper.postFormData(`${servicePath}/Delete`, requestData);
      multipleSelection.value.forEach(x => {
        var index = listDatas.value.findIndex(m => m == x);
        if (index >= 0) {
          listDatas.value.splice(index, 1);
        }

      });
      multipleTableRef.value?.clearSelection();
    } catch (error) {
      Global.showError(error);
    }
    finally {
      isLoading.value = false;
    }
  }
}

const handleSelectionChange = (selecteds: any[]) => {
  multipleSelection.value = selecteds;
}

const submitClick = async () => {
  try {
    await formRef.value?.validate();
  } catch (error) {
    return;
  }

  try {
    isBusy.value = true;
    if (formData.value.id) {
      var obj = JSON.parse( await HttpHelper.postJson(`${servicePath}/Modify`, formData.value) );
      listDatas.value.splice( listDatas.value.indexOf(editingData) , 1 , obj );
    }
    else {
      formData.value = JSON.parse( await HttpHelper.postJson(`${servicePath}/Add`, formData.value));
      listDatas.value.splice(0, 0, formData.value);
    }
    dialogFormVisible.value = false;
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isBusy.value = false;

  }
}

const goSearch = ()=>{
  pageNumber.value = 1; 
  bindList();
}
</script>
<template>
  <div class="page-view-main">
    <div style="padding: var(--page-padding);flex:1;min-height:0px;display: flex;flex-direction: column;">
      <div class="page-view-panel">
        <div style="display: flex;flex-direction: row;margin-bottom: 10px;">
          <div style="flex:1;">            
          </div>
          <div>
            <el-button-group class="ml-4">
              <el-button type="default" icon="Plus" @click="addClick">添加</el-button>
              <el-button type="default" icon="Refresh" @click="refreshClick">刷新</el-button>
              <el-button type="default" icon="Delete" @click="deleteClick">删除</el-button>
            </el-button-group>
          </div>
        </div>

        <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="listDatas"
          cell-class-name="tb-cell" header-cell-class-name="tb-header-cell" table-layout="auto" v-loading="isLoading"
          style="flex:1;min-height:0px;">
          <el-table-column type="selection" width="42" fixed="left" />
          <el-table-column prop="Name" label="代号" />
          <el-table-column prop="Caption" label="名称" />
          <el-table-column prop="CreateTime" label="创建时间" :formatter="Global.formatUTCToLocal" />
          <el-table-column prop="UpdateTime" label="更新时间" :formatter="Global.formatUTCToLocal" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editClick(scope.row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <Pagination @current-change="bindList" :total="total"
                    v-model:page-size="searchData.PageSize"  @size-change="refreshClick"
                        v-model:current-page="pageNumber" style="margin-top: 10px;" />
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="formData.id ? '编辑' : '新增'" :close-on-click-modal="false" width="500">
      <el-form ref="formRef" :model="formData" label-width="auto" :rules="rules" @keypress.native.enter.prevent="submitClick">
        <el-form-item label="代号" prop="Name">
          <el-input v-model="formData.Name" />
        </el-form-item>
        <el-form-item label="名称" prop="Caption">
          <el-input v-model="formData.Caption" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="isBusy" @click="submitClick">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">

</style>